package ro.one.gaeql.impl;

import java.util.Iterator;
import java.util.UUID;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;

public class JobEntity {
	private static final String PROP_ERROR = "error";
	private static final String PROP_STATE = "state";
	private static final String KIND = "Job";
	
	private String idJob;
	private Integer state;
	private String error = "(not set)";
	
	public JobEntity() {
		idJob = UUID.randomUUID().toString();
	}
	
	public String getIdJob() {
		return idJob;
	}

	public void setIdJob(String idJob) {
		this.idJob = idJob;
	}

	public Integer getState() {
		return state;
	}

	public void setState(Integer state) {
		this.state = state;
	}

	public void save() {
		Entity entity = new Entity(KeyFactory.createKey(KIND, idJob));
		entity.setProperty(PROP_STATE, state);
		entity.setProperty(PROP_ERROR, error);
		
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		ds.put(entity);
	}
	
	public static JobEntity get(String idJob) {
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		try {
			Entity entity = ds.get(KeyFactory.createKey(KIND, idJob));
			
			JobEntity result = new JobEntity();
			result.idJob = idJob;
			result.state = ((Long)entity.getProperty(PROP_STATE)).intValue();
			result.error = (String)entity.getProperty(PROP_ERROR);
			
			return result;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}

	public static Iterator<Entity> getJobs() {
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		Query q = new Query(KIND);
		q.setKeysOnly();

		return ds.prepare(q).asIterator();
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}
}
